package Threads.CAS;

import com.sun.javaws.exceptions.ErrorCodeResponseException;
import sun.misc.Unsafe;

public class MyAtomiacInteger {
    private volatile int val;
    static final Unsafe unsafe;
    static final long DATA_OFFSET;

    static {
        unsafe=UnsafeAccessor.getUnsafe();
        try {
            DATA_OFFSET=unsafe.objectFieldOffset(MyAtomiacInteger.class.getDeclaredField("val"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
            throw new Error(e);
        }
    }

    public MyAtomiacInteger(int val){
        this.val=val;
    }


    public void decrease(int amount){
        int old;
        while (true){
            old=val;
            if (unsafe.compareAndSwapInt(this,DATA_OFFSET,old,old-amount))
                return;
        }
    }

    public int get(){
        return val;
    }
}
